package com.wasu.sdk_ott.http.network

import android.util.Log
import com.wasu.constant.TAG
import com.wasu.sdk_ott.http.network.interceptor.ErrorInterceptor
import com.wasu.sdk_ott.http.network.interceptor.HeadInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.X509TrustManager

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> okhttp 请求
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/8/25
 */
open class BaseRetrofitFactory(private val baseUrl : String? = null) {

    companion object{
        /**
         * 链接超时时间
         */
        private const val CONNECT_TIME_OUT = 5L

        /**
         * 内存读写时间
         */
        private const val READ_TIME_OUT = 5L
    }


    /**
     * 延迟初始化是为了保证可以正确调用到子类的 getBaseUrl()
     */
    private val mRetrofit by lazy(LazyThreadSafetyMode.PUBLICATION) {
        Retrofit.Builder()
            .client(builder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(baseUrl?: getBaseUrl())
            .build()
    }

    private val builder by lazy(LazyThreadSafetyMode.PUBLICATION) {
        val trustAllCert: X509TrustManager = object : X509TrustManager {
            override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
            }
            override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
            }
            override fun getAcceptedIssuers(): Array<X509Certificate> {
                return arrayOf()
            }
        }

        //新建log拦截器
        val loggingInterceptor = HttpLoggingInterceptor { message ->
            Log.d(
                "module_http", "OkHttp====Message:$message"
            )
        }
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        OkHttpClient.Builder().apply {
            sslSocketFactory(SSLSocketFactoryCompat(trustAllCert), trustAllCert)
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                // 超时重连
                .retryOnConnectionFailure(true)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(HeadInterceptor())
                .addInterceptor(ErrorInterceptor())
        }
    }

    /**
     * 动态设置域名
     */
    open fun getBaseUrl(): String{
        return baseUrl?: ""
    }

    fun <T> create(service : Class<T>) : T = mRetrofit.create(service)

    /**
     * retrofit 请求
     */
    fun <T> enqueue(
        call: Call<T>,
        success : (result: T) -> Unit,
        failure : (e: Throwable) -> Unit = {  },
        complete : () -> Unit = {  }
    ) {
        call.enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                response.body()?.let(success)?: Log.e(TAG, "response response is null")
                complete()
            }
            override fun onFailure(call: Call<T>, t: Throwable) {
                Log.e(TAG, "response error: $t")
                failure(t)
                complete()
            }
        })
    }

}